package org.grow.enter.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.enter.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author: xwg
 * @CreateDate: 2021/9/8
 */

@Service
public class Fourth extends OncePerRequestFilter {
//    /login?username=zhangsan  get
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        System.out.println("第四拦截期拦截到");
//        @GetMapping("/login)
//        @RequestParam("username")
        if (req.getRequestURI().equals("/login")
                && req.getMethod().equalsIgnoreCase("GET")){
            String username = req.getParameter("username");
            System.out.println("获取到的用户名 ："+username);
            Person person = new Person();
            person.setUsername(username);
            person.setSex(true);
            person.setAge(88);
            String s = objectMapper.writeValueAsString(person);
            System.out.println("json : "+s);
            res.getWriter().println(s);
//            res.flushBuffer();
//ResponseBody RequestBody
//            浏览器访问 localhost：xxxx/login?username=zhangsan  测试
            return;
        }
        filterChain.doFilter(req,res);
    }
}
